'''
Created on 04/05/2013

@author: jean
'''

from pm.models.Atributos import Atributos
from flask import Flask, session, redirect, url_for, escape, request,Response
from . import ensureParams
from pm.database import db
from pm import app
from . import jsonifiedview
from pm.models.TiposItemAtributo import TiposItemAtributo
from pm.models.TipoItem import TipoItem

'''
Metodo que lista las Atributos con que cuenta un determinado proyecto
este metodo recibe un id de proyecto para que se realice la consulta
'''


@app.route('/atributos/listaratributos', methods=['GET', 'POST']) 
@jsonifiedview
def listarAtributos():
    params = {'GET':request.args, 'POST':request.form}[request.method]
    atributos = Atributos.query
    atributos = atributos.filter(Atributos.nombre_atributo.like('%' + params['nombre_atributo'] + '%')) if 'nombre_atributo' in params else atributos
    atributos = atributos.filter(Atributos.tipo.like('%' + params['tipo'] + '%')) if 'tipo' in params else atributos 
    atributos = atributos.filter(Atributos.activo.like('%' + params['activo'] + '%')) if 'activo' in params else atributos
    return atributos.order_by(Atributos.id_atributo).all()

@app.route('/atributos/crear', methods=['GET', 'POST']) 
@jsonifiedview
def crearAtributo():
    '''
        Crea un nuevo Atributo
    '''
    params = {'GET':request.args, 'POST':request.form}[request.method]
    
    response = {}
    if not ensureParams(params,['nombre_atributo','tipo','valor', 'id_tipo_item']): 
        response ={"success" : False , "msg" : "Parametros Insuficientes"} 
        return response
    valor = str(params['valor'])
    try:
        atributo = Atributos(params['nombre_atributo'],params['tipo'],params['id_tipo_item'], valor ,True)
        db.session.add(atributo)
        db.session.commit()
        response ={"success" : True , "msg" : "Creacion exitosa"} 
        return response
    except Exception, e:
        db.session.rollback()
        response ={"success" : False , "msg" : "Error en la base de datos" + str(e)}
    return response 

@app.route('/atributos/modificar', methods=['GET', 'POST']) 
@jsonifiedview
def modificarAtributo():
    '''
        Modifica un nuevo Atributo
    '''
    params = {'GET':request.args, 'POST':request.form}[request.method]
    
    response = {}
    if not ensureParams(params,['id_atributo','nombre_atributo','activo', 'valor']): 
        response ={"success" : False , "msg" : "Parametros Insuficientes"} 
        return response   
    valor = str(params['valor'])      
    try:
        atributo = Atributos.query.filter(Atributos.id_atributo == params['id_atributo']).update({'nombre_atributo':params['nombre_atributo'],'activo':params['activo'], 'valor': valor})
        db.session.commit()
        response ={"success" : True , "msg" : "Actualizacion exitosa"}
        return response
    except Exception, e:
        db.session.rollback()
        response ={"success" : False , "msg" : "Error en la base de datos"}
        return response 

@app.route('/atributos/listardistinct',methods=['GET','POST'])
@jsonifiedview
def listarAtributosDistinct():
    """
        lista los atributos que no pertenecen a un tipo de item
    """
    params = {'GET':request.args, 'POST':request.form}[request.method]
    resp = []
    
    if not ensureParams(params,['id_tipo_item']): 
        return resp 
    atributos = Atributos.query.filter(Atributos.id_tipo_item != params['id_tipo_item']).filter(Atributos.activo == True).all()
    for a in atributos:
        tipoItem = TipoItem.query.filter(TipoItem.id_tipo_item == a.id_tipo_item).one()
        if tipoItem.activo == True:
            resp.append(a)
                
    return resp

@app.route('/atributos/listaratributosbytipoitem',methods=['GET','POST'])
@jsonifiedview
def listarAtributosByTipoItem():
    """
        lista los atributos de un tipo de item dado
    """
    params = {'GET':request.args, 'POST':request.form}[request.method]
    resp = []
    
    if not ensureParams(params,['id_tipo_item']): 
        return resp 
    
    atributos = Atributos.query
    atributos = atributos.filter(Atributos.id_tipo_item == params ['id_tipo_item']).filter(Atributos.activo == True)
    atributos = atributos.filter(Atributos.nombre_atributo.like('%' + params['nombre_atributo'] + '%')) if 'nombre_atributo' in params else atributos
    atributos = atributos.filter(Atributos.tipo == params['tipo']) if 'tipo' in params else atributos 
    atributos = atributos.all()
    
    for a in atributos:
        resp.append(a)
                
    return resp

@app.route('/atributos/importar',methods=['GET','POST'])
@jsonifiedview
def importarAtributo():
    '''
        importa en un tipo de item un atributo
        @param id_tipo_item = el item donde se va a importar el atributo
        @param id_atributo = el id del atributo a ser importado
    '''
    params = {'GET':request.args, 'POST':request.form}[request.method]
    
    response = {}
    if not ensureParams(params,['id_tipo_item','id_atributo']): 
        response ={"success" : False , "msg" : "Parametros Insuficientes"} 
        return response
    try:   
        atributo = Atributos.query.filter(Atributos.id_atributo == params['id_atributo']).one()
        atributoNuevo = Atributos(atributo.nombre_atributo, atributo.tipo, params['id_tipo_item'], atributo.valor, True)
        db.session.add(atributoNuevo)
        db.session.commit()
        response ={"success" : True , "msg" : "Importacion exitosa"} 
        return response
    except Exception, e:
        print e
        db.session.rollback()
        response ={"success" : False , "msg" : "Ups, ha ocurrido un error"} 
        return response
        
